package com.fatcat.easybuy.controller;

import com.fatcat.easybuy.config.VXConfig;
import com.fatcat.easybuy.service.impl.AiPayServiceImpl;
import com.fatcat.easybuy.util.ResponseResult;
import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/VXpay")
public class VXpayController {
    private static final Logger logger = LoggerFactory.getLogger(VXpayController.class);

    private final NativePayService nativePayService;
    private final VXConfig vxConfig;
    private final NotificationParser notificationParser;
    @Autowired
    private AiPayServiceImpl aiPayService;

    @Autowired
    public VXpayController(VXConfig vxConfig) {
        this.vxConfig = vxConfig;
        this.nativePayService = new NativePayService.Builder()
                .config(vxConfig.getConfig())
                .build();
        this.notificationParser = new NotificationParser(vxConfig.getConfig());
    }

    @PostMapping("/VXPayment")
    public ResponseResult VXPayment(@RequestBody Map<String, String> params) {
        //创建支付对象
        PrepayRequest request = new PrepayRequest();

        Amount amount = new Amount();
        amount.setTotal(1); // 单位：分
        request.setAmount(amount);

        request.setAppid(vxConfig.getAppid()); // 微信AppID
        request.setMchid(vxConfig.getMerchantId()); // 商户号
        request.setDescription(params.get("Description")); // 商品描述
        request.setNotifyUrl(vxConfig.getNotifyUrl()); // 支付结果回调地址
        request.setOutTradeNo(params.get("outTradeNo")); // 商户订单号

        try {
            PrepayResponse response = nativePayService.prepay(request);
            return ResponseResult.success().add("pay_url", response.getCodeUrl());
        } catch (Exception e) {
            logger.error("微信支付下单失败", e);
            return ResponseResult.error("微信支付下单失败: " + e.getMessage());
        }
    }

    @PostMapping("/wxNotify")
    public void wxNotify(@RequestHeader(value = "Wechatpay-Signature") String signature,
                         @RequestHeader(value = "Wechatpay-Serial") String serialNumber,
                         @RequestHeader(value = "Wechatpay-Timestamp") String timestamp,
                         @RequestHeader(value = "Wechatpay-Nonce") String nonce,
                         @RequestHeader(value = "Wechatpay-Signature-Type") String signatureType,
                         @RequestBody String body,
                         HttpServletResponse response) {


        RequestParam requestParam = new RequestParam.Builder()
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .serialNumber(serialNumber)
                .signType(signatureType)
                .body(body)
                .build();

        try {
            Transaction transaction = notificationParser.parse(requestParam, Transaction.class);

            if (transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
                logger.info("支付成功，商户订单号: {}, 微信交易号: {}",
                        transaction.getOutTradeNo(),
                        transaction.getTransactionId());
                if(aiPayService.handlePayNotify(transaction.getOutTradeNo(), transaction.getTransactionId())) {
                    logger.info("数据库操作成功");

                }else {
                    throw new RuntimeException("数据库操作失败");
                }
            }

            response.setStatus(200);
        } catch (ValidationException e) {
            logger.error("验证签名错误", e);
            response.setStatus(500);
        }
    }
}